package com.easyj.base.security.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.easyj.base.common.ajax.Result;
import com.easyj.base.security.service.JCacheSecurityService;
import com.easyj.base.security.service.TokenUtil;
import com.wf.captcha.ArithmeticCaptcha;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping(value = "/auth")
public class AuthController {
	public Logger log =  LoggerFactory.getLogger(getClass());

	@Autowired 
	private  JCacheSecurityService securityService;
   
	
	
	@GetMapping(value = "/code")
    public Result getCode(){
        ArithmeticCaptcha captcha = new ArithmeticCaptcha(111, 36);
        // 几位数运算，默认是两位
        captcha.setLen(2);
        // 获取运算的结果：5
        String result = captcha.text();
        String uuid = UUID.randomUUID().toString();
        securityService.setCaptchaCode(uuid, result);
        CaptchaResult r=new CaptchaResult();
        r.setImg(captcha.toBase64());
        r.setUuid(uuid);
        return Result.Success(r);
    }
	
	@GetMapping(value = "/toLogin")
    public Result toLogin(){
        //返回错误401，路由到登录页面
        return Result.Error(401, "会话超时或未登录");
    }
	
	
	
	
	@DeleteMapping(value = "/logout")
    public Result logout(HttpServletRequest request){
        try {
        	securityService.deleteOnlineUser(TokenUtil.getToken(request));
			 
		} catch (Exception e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
        return Result.Success();
    }
	
	
	private class CaptchaResult {

	    private String img;

	    private String uuid;

		public String getImg() {
			return img;
		}

		public void setImg(String img) {
			this.img = img;
		}

		public String getUuid() {
			return uuid;
		}

		public void setUuid(String uuid) {
			this.uuid = uuid;
		}
	    
	}
}
